const RBAC = require('rbac-a');
const Provider = RBAC.providers.JsonProvider;


module.exports = function (options, app) {
    const rules = options.rabc;
    // const rules = await require('./rules')();
    RBAC.prototype.checkByCode = async function (user, code, module) {

        const Permission = think.mongoose('Permission', {}, 'admin');
        const entity = await Permission.findOne({code: code, module: module}).exec();
        if (entity) {
            think.logger.info(`检查权限：id:${entity['id']},code:${entity['code']},title:${entity['title']},module:${entity['module']}`);
            const permissionId = entity['_id'].toString();
            return this.check(user, permissionId);
        }
        return 0;
    };

    //注入权限检查机制
    think.rbac = new RBAC({
        provider: new Provider(rules)
    });

    return async (ctx, next) => {

        const module = ctx.module;
        const controller = ctx.controller;
        const action = ctx.action;


        //检测模块是否安装
        if (['admin', 'public', 'favicon.ico'].indexOf(module) === -1) { //不需要安装的系统模块
            const Module = think.mongoose('Module', {}, 'admin');
            const entity = await Module.findOne({name: module, isSetup: true}).exec();
            if (! entity) {
                // think.logger.warn(`模块${module}没有安装`);
                ctx.throw(401, `没有安装模块：${module}`);
            }
        }

        if (ctx.url.match(/^\/admin\/public/)) {
            //注册登录

        } else if (ctx.url.match(/^\/admin\/index\/index/)) {

        } else if (ctx.url.match(/^\/api/)) {
            //API使用jwt中间件检查权限，属于前台接口


            // } else if (ctx.url.match(/^\/admin/)) {
        }else {
            //检测登录的用户id
            let adminId;
            if (ctx.state.admin && ctx.state.admin._id) {
                adminId = ctx.state.admin._id.toString();
            }
            // console.log(adminId);
            if (adminId) {
                //超级管理员不检测菜单访问权限，否则系统没法配置
                if (['system'].indexOf(ctx.state.admin.username) !== -1) {

                } else {
                    const Administrator = think.mongoose('Administrator', {}, 'admin');
                    const path = `/${module}/${controller}/${action}`;

                    if (!await Administrator.checkMenuAccessPermissionByPath(adminId, path)) {
                        ctx.throw(401, `没有授权访问”${path}“`);
                    }
                }
            }
        }

        return next();
    }
};
